package handlers

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"
	"werewolf/core"

	"golang.org/x/exp/rand"
)

func CreateHandler(w http.ResponseWriter, r *http.Request) { //  处理创建房间请求
	fmt.Println("CreateHandler")
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		fmt.Println("CreateHandler: Invalid request method")
		return
	}

	r.ParseForm()
	post := r.PostForm
	addRole := ""
	roleNo := 0
	// Collect roles from the form
	for key := range post {
		if key != "n-werewolf" && key != "n-folk" && key != "username" && key != "aiEnabled" {
			if post.Get(key) == "true" {
				addRole += key + ";"
				roleNo++ //统计人数
			}
		}
	}
	addRole = strings.TrimSuffix(addRole, ";")

	werewolves := post.Get("n-werewolf") //得到字符串
	folks := post.Get("n-folk")

	rand.Seed(uint64(time.Now().UnixNano())) //随机数种子
	roomNo := rand.Intn(100)
	creator := post.Get("username")

	wn0, _ := strconv.Atoi(werewolves)
	fn0, _ := strconv.Atoi(folks)
	roleNo += wn0 + fn0

	handle, err := core.Connection()
	if err != nil {
		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
		fmt.Println("CreateHandler: Connection failed: ")
		return
	}
	defer handle.Close()

	if err = handle.Ping(); err != nil {
		http.Error(w, "Connection is not available: "+err.Error(), http.StatusInternalServerError)
		fmt.Println("CreateHandler: Connection is not available:", err)
		return
	}

	// Start a transaction
	tx, err := handle.Begin()
	if err != nil {
		http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)
		fmt.Println("CreateHandler: Error starting transaction: ")
		return
	}

	// Check if the room already exists
	var existingRoom int
	err = tx.QueryRow("SELECT RmNo FROM Game WHERE RmNo=?", roomNo).Scan(&existingRoom)
	if err != nil && err != sql.ErrNoRows {
		tx.Rollback()
		http.Error(w, "Error checking existing room: "+err.Error(), http.StatusInternalServerError)
		fmt.Println("CreateHandler: Error checking existing room: ")
		return
	}

	// If the room exists, delete existing entries
	if err == nil {
		_, err = tx.Exec("DELETE FROM Game WHERE RmNo=?", roomNo)
		if err != nil {
			tx.Rollback()
			http.Error(w, "Error deleting from Game: "+err.Error(), http.StatusInternalServerError)
			return
		}

		_, err = tx.Exec("DELETE FROM Running WHERE RmNo=?", roomNo)
		if err != nil {
			tx.Rollback()
			http.Error(w, "Error deleting from Running: "+err.Error(), http.StatusInternalServerError)
			return
		}

		_, err = tx.Exec("DELETE FROM Player WHERE RmNo=?", roomNo)
		if err != nil {
			tx.Rollback()
			http.Error(w, "Error deleting from Player: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}

	// Insert new game

	_, err = tx.Exec("INSERT INTO Game VALUES(?, ?, ?, ?, ?, ?, '0', 0, ?)", roomNo, addRole, werewolves, folks, roleNo, creator, creator)
	if err != nil {
		tx.Rollback()
		http.Error(w, "Error inserting into Game: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Insert into Running table
	_, err = tx.Exec("INSERT INTO Running (RmNo, death1, death2, death3, start, voting) VALUES (?, 0, 0, 0, 0, 0)", roomNo)
	if err != nil {
		tx.Rollback()
		http.Error(w, "Error inserting into Running: "+err.Error(), http.StatusInternalServerError)
		return
	}

	// Update Running table for roles
	for key := range post {
		if key != "n-werewolf" && key != "n-folk" && key != "username" && key != "aiEnabled" {
			updateStr := fmt.Sprintf("UPDATE Running SET `%s`=0 WHERE RmNo=%d", key, roomNo) //初始化Running表
			_, err = tx.Exec(updateStr)
			if err != nil {
				tx.Rollback()
				http.Error(w, "Error updating Running for role: "+err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}

	//根据是否有ai玩家参与，决定是否给ai玩家分配角色
	//
	if post.Get("aiEnabled") == "yes" {
		fmt.Println("Create Rooom with ai enabled")
		var roles []string
		if addRole != "" {
			roles = strings.Split(addRole, ";")
		}
		//此处加入了所有特殊角色
		countInt, err := strconv.Atoi(werewolves)
		if err != nil {
			fmt.Println("Error converting werewolves to int:", err)
			return // 或者根据你的需求处理错误
		}
		for i := 0; i < countInt; i++ {
			roles = append(roles, "w")
		}
		countInt, err = strconv.Atoi(folks)
		if err != nil {
			fmt.Println("Error converting folks to int:", err)
			return // 或者根据你的需求处理错误
		}
		for i := 0; i < countInt; i++ {
			roles = append(roles, "f")
		} //加入普通狼和平民

		aiusername := "kimi-gpt"
		newRole := rand.Intn(roleNo) + 1
		_, err = tx.Exec("INSERT INTO Player (Username, Name, RmNo, Role, No, Survival, Vote) VALUES (?, '', ?, ?, 1, 1, 0)", aiusername, roomNo, newRole)
		if err != nil {
			fmt.Println("Error inserting player:", err)
			// 尝试更新操作
			_, err := handle.Exec("UPDATE Player SET Role=?, No=?, Survival=1, RmNo=?, Vote=0 WHERE Username=?", newRole, 1, roomNo, aiusername)
			if err != nil {
				http.Error(w, "Error updating player: "+err.Error(), http.StatusInternalServerError)
				return
			}
		}

		//对话ai，游戏开始
		//判断预言家和女巫、狼王、猎人、守卫、恶魔、骑士的人数
		seerint := 0
		witchint := 0
		guardint := 0
		hunterint := 0
		knightint := 0
		wolvekingint := 0
		wolveknightint := 0
		devilint := 0
		for role := range roles { //返回索引int
			if roles[role] == "g-seer" {
				seerint++
			} else if roles[role] == "g-witch" {
				witchint++
			} else if roles[role] == "g-guard" {
				guardint++
			} else if roles[role] == "g-hunter" {
				hunterint++
			} else if roles[role] == "w-devil" {
				devilint++
			} else if roles[role] == "w-king" {
				wolvekingint++
			} else if roles[role] == "w-knight" {
				wolveknightint++
			} else if roles[role] == "g-knight" {
				knightint++
			}
		}

		//fmt.println("seerint:", seerint)
		fmt.Println(roomNo)
		fmt.Println(newRole)
		fmt.Println(roles[newRole-1])
		//插入该房间的ai信息到ai信息记录表
		_, err = tx.Exec("INSERT INTO ai_info (RmNo, AiId, RoleInt, Role) VALUES (?, ?, ?, ?)", roomNo, 1, newRole, roles[newRole-1])
		if err != nil {
			fmt.Println("error insert ai_info")
			fmt.Println(err)
			http.Error(w, "Error inserting into ai_info: "+err.Error(), http.StatusInternalServerError)
			return
		}
		kimirespone := gamePreparation(roomNo, roleNo, fn0, wn0, seerint, witchint, guardint, hunterint, knightint, wolvekingint, devilint, wolveknightint)
		//对ai进行初始化尝试连接
		if !kimirespone {
			http.Error(w, "Error initializing ai", http.StatusInternalServerError) //告知ai初始化失败
		}

	}

	// Commit the transaction
	if err := tx.Commit(); err != nil {
		http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)
		return
	}

	response := make(map[string]interface{})
	response["room"] = roomNo
	response["user"] = creator

	json.NewEncoder(w).Encode(response)

}
